package com.hmall.order.config;

import com.hmall.order.constant.OrderMQConstant;
import org.springframework.amqp.core.*;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class OrderRabbitConfig {
    /**
     * 下单交换机
     */
    @Bean
    public DirectExchange orderExchange() {
        return new DirectExchange(
                OrderMQConstant.ORDER_EXCHANGE,
                true,
                false
        );
    }

    /**
     * 延时队列
     */
    @Bean
    public Queue delayQueue() {
        //注意：过期时间只在第一次创建队列时应用，如果修改了时间，要确保在MQ控制台删除这个队列，再次启动微服务，才会重新应用最新时间
        //正式：30分钟
        //int ttl = 1000 * 60 * 30;
        //测试：5秒
        int ttl = 1000 * 20;
        return QueueBuilder
                .durable(OrderMQConstant.ORDER_QUEUE)
                //过期时间，单位为毫秒
                .ttl(ttl)
                //指定死信交换机
                .deadLetterExchange(OrderMQConstant.DEAD_LETTER_EXCHANGE)
                //指定死信路由key
                .deadLetterRoutingKey(OrderMQConstant.DEAD_LETTER_ROUTING_KEY)
                .build();
    }

    /**
     * 绑定延时队列和下单交换机
     */
    @Bean
    public Binding bindDelayQueueToExchange(DirectExchange orderExchange, Queue delayQueue) {
        return BindingBuilder
                .bind(delayQueue)
                .to(orderExchange)
                .with(OrderMQConstant.ORDER_ROUTING_KEY);
    }

    /**
     * 创建死信交换机
     */
    @Bean
    public DirectExchange deadLetterExchange() {
        return new DirectExchange(OrderMQConstant.DEAD_LETTER_EXCHANGE, true, false);
    }

    /**
     * 创建死信队列
     */
    @Bean
    public Queue deadLettterQueue() {
        return QueueBuilder
                .durable(OrderMQConstant.DEAD_LETTER_QUEUE)
                .build();
    }

    /**
     * 绑定死信队列和死信交换机
     */
    @Bean
    public Binding bindQueueToExchange(DirectExchange deadLetterExchange, Queue deadLettterQueue) {
        return BindingBuilder
                .bind(deadLettterQueue)
                .to(deadLetterExchange)
                .with(OrderMQConstant.DEAD_LETTER_ROUTING_KEY);
    }
}